import BigNumber from "bignumber.js"

let tool = {
  // 断网
  isHaveNetwork() {
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType == "none") {
          uni.showModal({
            title: "当前无网络连接!",
            content: "请您检查网络是否链接正常!请打开WIFI或者移动数据。",
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: "/pages/404/404.vue",
                })
              } else {
                uni.navigateTo({
                  url: "/pages/404/404.vue",
                })
              }
            },
          })
        } else {
          console.log("网络已连接,可以正常访问!") //有网
        }
        setTimeout(function () {
          return res.networkType
        }, 500)
      },
    })
  },

  /**
   * 参数处理
   * @param params 参数
   */
  tansParams(params) {
    let result = ""
    for (const propName of Object.keys(params)) {
      const value = params[propName]
      var part = encodeURIComponent(propName) + "="
      if (value !== null && value !== "" && typeof value !== "undefined") {
        if (typeof value === "object") {
          for (const key of Object.keys(value)) {
            if (value[key] !== null && value[key] !== "" && typeof value[key] !== "undefined") {
              let params = propName + "[" + key + "]"
              var subPart = encodeURIComponent(params) + "="
              result += subPart + encodeURIComponent(value[key]) + "&"
            }
          }
        } else {
          result += part + encodeURIComponent(value) + "&"
        }
      }
    }
    return result
  },
  formatNumber(value, options) {
    options = options || {
      FORMAT: {
        decimalSeparator: ".",
        groupSeparator: ",",
        groupSize: 3,
      },
    }
    BigNumber.config(options)

    const num = new BigNumber(value)
    return value? num.decimalPlaces(2, BigNumber.ROUND_DOWN).toFormat(2) : '0.00' // 保留2位小数并添加千分位
  },
  formatToYuan(value) {
    return value ? new BigNumber(value).dividedBy(100).toNumber() : "0.00"
  },
}

export default tool
